<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 合同信息 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div v-if="advancedSearch" class="handle-box">
                <el-form inline v-model="query" label-width="100px">
                    <el-form-item label="合同类别">
                        <el-select v-model="query.typeName" clearable placeholder="请选择" @change="getContractData">
                            <el-option
                                v-for="item in contractTypes"
                                :key="item.typeId"
                                :label="item.typeName"
                                :value="item.typeName"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属部门">
                        <el-select v-model="query.departName" clearable placeholder="请选择" @change="getContractData">
                            <el-option
                                v-for="item in departs"
                                :key="item.departId"
                                :label="item.departName"
                                :value="item.departName"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="创建人">
                        <el-select v-model="query.createUser" clearable placeholder="请选择" @change="getContractData">
                            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="审核人">
                        <el-select v-model="query.approvalPerson" clearable placeholder="请选择" @change="getContractData">
                            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="最后编辑人">
                        <el-select v-model="query.editedUser" clearable placeholder="请选择" @change="getContractData">
                            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="采用模板">
                        <el-select v-model="query.templateName" clearable placeholder="请选择" @change="getContractData">
                            <el-option
                                v-for="item in contractTemplates"
                                :key="item.templateId"
                                :label="item.templateName"
                                :value="item.templateName"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="完成状态">
                        <el-radio-group @change="getContractData" v-model="query.completed">
                            <el-radio :label="0">未完成</el-radio>
                            <el-radio :label="1">已完成</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="审核状态">
                        <el-radio-group @change="getContractData" v-model="query.passed">
                            <el-radio :label="0">未通过</el-radio>
                            <el-radio :label="1">已通过</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </div>
            <div class="handle-box">
                <el-input v-model="query.contractName" placeholder="合同名称" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="getContractData">搜索</el-button>
                <el-button v-if="advancedSearch === false" type="primary" @click="handleAdvancedSearch">高级查询</el-button>
                <el-button icon="el-icon-back" v-if="advancedSearch === true" type="primary" @click="handleAdvancedSearch">还原</el-button>
                <el-button icon="el-icon-refresh" v-if="advancedSearch === true" type="primary" @click="clearAdvancedSearch"
                    >清空</el-button
                >
            </div>
            <el-table :data="contractData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-form label-position="left" inline class="demo-table-expand">
                            <el-form-item label="合同ID">
                                <span>{{ scope.row.contractId }}</span>
                            </el-form-item>
                            <el-form-item label="合同名称">
                                <span>{{ scope.row.contractName }}</span>
                            </el-form-item>
                            <el-form-item label="合同类型">
                                <span>{{ scope.row.contractType }}</span>
                            </el-form-item>
                            <el-form-item label="所属部门">
                                <span>{{ scope.row.depart }}</span>
                            </el-form-item>
                            <el-form-item label="甲方公司">
                                <span>{{ scope.row.companiesA }}</span>
                            </el-form-item>
                            <el-form-item label="乙方公司">
                                <span>{{ scope.row.companiesB }}</span>
                            </el-form-item>
                            <el-form-item label="签订时间">
                                <span>{{ scope.row.startTime }}</span>
                            </el-form-item>
                            <el-form-item label="到期时间">
                                <span>{{ scope.row.endTime }}</span>
                            </el-form-item>

                            <el-form-item label="当前金额">
                                <span>￥{{ scope.row.currentAmount }}</span>
                            </el-form-item>
                            <el-form-item label="合同金额">
                                <span>￥{{ scope.row.contractAmount }}</span>
                            </el-form-item>
                            <el-form-item label="创建人">
                                <span>{{ scope.row.createUser }}</span>
                            </el-form-item>
                            <el-form-item label="创建时间">
                                <span>{{ scope.row.createTime }}</span>
                            </el-form-item>
                            <el-form-item label="负责人/手机">
                                <span>{{ scope.row.contactInfo }}</span>
                            </el-form-item>

                            <el-form-item label="采用模板">
                                <span>{{ scope.row.templateName }}</span>
                            </el-form-item>
                            <div>
                                <el-form-item
                                    v-for="(item, index) in scope.row.externList"
                                    :key="index"
                                    :label="'字段' + index + ' ' + item.name"
                                >
                                    <span>{{ item.value }}</span>
                                </el-form-item>
                            </div>
                            <div>
                                <el-form-item label="最后编辑人">
                                    <span>{{ scope.row.lastEditedUser }}</span>
                                </el-form-item>
                                <el-form-item label="编辑时间">
                                    <span>{{ scope.row.editedTime }}</span>
                                </el-form-item>
                            </div>
                            <div>
                                <el-form-item label="审批人员">
                                    <span>{{ scope.row.approvalPerson }}</span>
                                </el-form-item>
                                <el-form-item label="通过时间">
                                    <span>{{ scope.row.passedTime }}</span>
                                </el-form-item>
                                <el-form-item label="审批意见">
                                    <span>{{ scope.row.approvalContent }}</span>
                                </el-form-item>
                            </div>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="contractId" label="ID" width="100" align="left" show-overflow-tooltip></el-table-column>
                <el-table-column prop="contractName" label="合同名称"></el-table-column>
                <el-table-column prop="contractType" label="合同类型"></el-table-column>
                <el-table-column prop="depart" label="所属部门"></el-table-column>
                <el-table-column prop="contactInfo" label="负责人/电话"></el-table-column>
                <el-table-column prop="createUser" label="创建人"></el-table-column>
                <el-table-column label="收支进度">
                    <template slot-scope="scope">
                        <el-progress :percentage="getPercentage(scope.$index, scope.row)" :color="customColorMethod"> </el-progress>
                        <el-tag v-if="statusTag(scope.$index, scope.row) === false && scope.row.completed === 0">执行中</el-tag>
                        <el-tag type="danger" v-if="statusTag(scope.$index, scope.row) === true && scope.row.completed === 0"
                            >已逾期</el-tag
                        >
                        <el-tag type="success" v-if="scope.row.completed === 1">已结束</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="完成状态" width="100" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.completed === 1" type="success">已完成</el-tag>
                        <el-tag v-if="scope.row.completed === 0" type="danger">未完成</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" width="100" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.passed === -1" type="danger">被拒绝</el-tag>
                        <el-tag v-if="scope.row.passed === 1" type="success">已通过</el-tag>
                        <el-tag v-if="scope.row.passed === 0">等待审批</el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="100" align="center">
                    <template slot-scope="scope">
                        <el-dropdown>
                            <span class="el-dropdown-link">操作<i class="el-icon-arrow-down el-icon--right"></i> </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item icon="el-icon-edit" @click.native="handleEditContract(scope.$index, scope.row)"
                                    >合同编辑</el-dropdown-item
                                >
                                <el-dropdown-item icon="el-icon-files" @click.native="handleManageAttachment(scope.$index, scope.row)"
                                    >合同附件</el-dropdown-item
                                >
                                <el-dropdown-item icon="el-icon-money" @click.native="handleManageStatus(scope.$index, scope.row)"
                                    >合同收支
                                </el-dropdown-item>
                                <el-dropdown-item icon="el-icon-delete" @click.native="handleDelete(scope.$index, scope.row)"
                                    >合同删除</el-dropdown-item
                                >
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page.sync="pageParams.currentPage"
                    :page-size.sync="pageParams.pageSize"
                    :page-count="pageParams.totalElements"
                    :total="pageParams.totalElements"
                    @current-change="getContractData"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑/审核" :visible.sync="editVisible" width="90%">
            <div>
                <el-form ref="formData" :model="formData" label-width="120px" label-position="left" :rules="rules">
                    <div class="form-box">
                        <el-form-item prop="contractName" label="合同名称">
                            <el-input disabled v-model="formData.contractName"></el-input>
                        </el-form-item>
                        <el-form-item prop="contractType" label="合同类型">
                            <el-select v-model="formData.contractType" placeholder="请选择">
                                <el-option
                                    v-for="item in contractTypes"
                                    :key="item.typeId"
                                    :label="item.typeName"
                                    :value="item.typeId"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="depart" label="所属部门">
                            <el-select v-model="formData.depart" placeholder="请选择">
                                <el-option
                                    v-for="item in departs"
                                    :key="item.departName"
                                    :label="item.departName"
                                    :value="item.departId"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="contactPerson" label="负责人/电话">
                            <el-select v-model="formData.contactInfo" placeholder="请选择">
                                <el-option
                                    v-for="item in users"
                                    :key="item.id"
                                    :label="item.username + '/' + item.phone"
                                    :value="item.username + '/' + item.phone"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="companiesA" label="甲方公司">
                            <el-select v-model="formData.companiesA" multiple placeholder="请选择">
                                <el-option
                                    v-for="item in companies"
                                    :key="item.companyName"
                                    :label="item.companyName"
                                    :value="item.companyId"
                                    :disabled="formData.companiesB.some((e) => e == item.companyId) === true"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="signedDate" label="签订时间">
                            <el-col :span="11">
                                <el-date-picker
                                    type="date"
                                    placeholder="选择日期"
                                    v-model="formData.startTime1"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%"
                                ></el-date-picker>
                            </el-col>
                            <el-col class="line" :span="2">-</el-col>
                            <el-col :span="11">
                                <el-time-picker placeholder="选择时间" v-model="formData.startTime2" style="width: 100%"></el-time-picker>
                            </el-col>
                        </el-form-item>
                        <el-form-item prop="passed" label="审批状态">
                            <el-radio-group v-model="formData.passed">
                                <el-radio :disabled="loginUser.usertype !== 0" :label="0">未通过</el-radio>
                                <el-radio :disabled="loginUser.usertype !== 0" :label="1">已通过</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>

                    <div class="form-box">
                        <el-form-item clearable prop="contractTemplate" label="合同模板">
                            <el-select disabled v-model="formData.templateId" filterable clearable placeholder="请选择">
                                <el-option
                                    v-for="item in contractTemplates"
                                    :key="item.templateId"
                                    :label="item.templateName"
                                    :value="item.templateId"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="合同金额">
                            <el-input-number
                                size="medium"
                                v-model="formData.contractAmount"
                                :precision="2"
                                :step="1"
                                :min="0"
                            ></el-input-number>
                        </el-form-item>
                        <el-form-item prop="externString" label="额外字段">
                            <el-input disabled v-model="formData.externString" style="width: 70%"></el-input>
                            <el-button type="primary" style="margin: 0px 0px 0px 10px" @click="handleEditExtern">添加</el-button>
                        </el-form-item>
                        <el-form-item label="录入人员" style="width: 50%">
                            <el-input v-model="formData.createUser" disabled></el-input>
                        </el-form-item>

                        <el-form-item prop="companiesB" label="乙方公司">
                            <el-select v-model="formData.companiesB" multiple placeholder="请选择">
                                <el-option
                                    v-for="item in companiesB"
                                    :key="item.companyId"
                                    :label="item.companyName"
                                    :value="item.companyId"
                                    :disabled="formData.companiesA.some((e) => e === item.companyId) === true"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="deadline" label="到期时间">
                            <el-col :span="11">
                                <el-date-picker
                                    type="date"
                                    placeholder="选择日期"
                                    v-model="formData.endTime1"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%"
                                ></el-date-picker>
                            </el-col>
                            <el-col class="line" :span="2">-</el-col>
                            <el-col :span="11">
                                <el-time-picker placeholder="选择时间" v-model="formData.endTime2" style="width: 100%"></el-time-picker>
                            </el-col>
                        </el-form-item>

                        <el-form-item prop="completed" label="完成状态">
                            <el-radio-group v-model="formData.completed">
                                <el-radio :label="0">未完成</el-radio>
                                <el-radio :label="1">已完成</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>
                    <div class="form-box">
                        <el-form-item prop="contractName" label="审批意见">
                            <el-input
                                :disabled="loginUser.usertype !== 0"
                                type="textarea"
                                rows="4"
                                v-model="formData.approvalContent"
                            ></el-input>
                        </el-form-item>
                    </div>
                </el-form>
                <div style="text-align: center">
                    <el-button type="primary" @click="handleSaveEdit">编辑</el-button>
                    <el-button @click="handleCancel">取消</el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog title="额外字段" :visible.sync="externVisible" width="50%">
            <el-form :inline="true" :model="formData" label-width="80px">
                <div v-for="(item, index) in formData.externList" :key="item.key">
                    <el-form-item
                        :label="'字段' + index"
                        :prop="'externList.' + index + '.name'"
                        :rules="[{ required: true, message: '字段不能为空', trigger: 'blur' }]"
                    >
                        <el-input v-model="item.name" placeholder="输入字段名"> </el-input>
                    </el-form-item>
                    <el-form-item
                        :label="'内容' + index"
                        :prop="'externList.' + index + '.value'"
                        :rules="[{ required: true, message: '内容不能为空', trigger: 'blur' }]"
                    >
                        <el-input v-model="item.value" placeholder="输入内容"> </el-input>
                    </el-form-item>
                    <el-button style="margin: 0px 10px" @click.prevent="removeExtern(item)">删除</el-button>
                </div>
                <div style="text-align: center">
                    <el-form-item>
                        <el-button type="primary" @click="closeExtern">确定</el-button>
                        <el-button @click="addExtern">新增</el-button>
                        <el-button @click="resetExtern">重置</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
//import { fetchData } from '../../api/index';
import { dateToString, getFromDateAndTime } from '../../util/DateUtil.js';
import { get, post, put } from '../../api/http.js';
import * as api from '@/api/index.js';
export default {
    name: 'contractInfo',
    data() {
        var checkSignedDate = (rule, value, callback) => {
            let date1 = this.formData.startTime1;
            let date2 = this.formData.startTime2;
            let date3 = this.formData.endTime1;
            let date4 = this.formData.endTime2;
            this.$forceUpdate();
            if (date1 === '' || !date1) {
                callback(new Error('请输入日期'));
            }
            if (date2 === '' || !date2) {
                callback(new Error('请输入时间'));
            }

            if ((date1 !== '' || date1) && (date2 !== '' || date2) && (date3 !== '' || date3) && (date4 !== '' || date4)) {
                let start = getFromDateAndTime(date1, date2);
                let end = getFromDateAndTime(date3, date4);
                if (start.getTime() > end.getTime()) {
                    callback(new Error('签约时间不能迟于截止时间'));
                }
            }
            callback();
        };
        var checkDeadline = (rule, value, callback) => {
            let date1 = this.formData.endTime1;
            let date2 = this.formData.endTime2;
            let date3 = this.formData.startTime1;
            let date4 = this.formData.startTime2;
            this.$forceUpdate();
            if (date1 === '' || !date1) {
                callback(new Error('请输入日期'));
            }
            if (date2 === '' || !date2) {
                callback(new Error('请输入时间'));
            }
            if ((date1 !== '' || date1) && (date2 !== '' || date2) && (date3 !== '' || date3) && (date4 !== '' || date4)) {
                let start = getFromDateAndTime(date1, date2);
                let end = getFromDateAndTime(date3, date4);
                if (start.getTime() < end.getTime()) {
                    callback(new Error('截止时间不能早于签订时间'));
                }
            }
            callback();
        };
        var checkExtern = (rule, value, callback) => {
            let list = this.formData.externList;
            let len = list.length;
            for (let i = 0; i < len; i++) {
                if (list[i].name === '' || list[i].value === '') {
                    callback(new Error('请完善字段'));
                }
                if (list[i].name !== '' && list[i].value !== '') {
                    for (let j = 0; j < len && i !== j; j++) {
                        if (list[i].name === list[j].name) {
                            callback(new Error('字段名称存在重复'));
                        }
                    }
                }
            }
            callback();
        };
        return {
            externVisible: false,
            editVisible: false,
            query: {
                contractName: '',
                typeName: '',
                departName: '',
                createUser: '',
                contactPerson: '',
                approvalPerson: '',
                editedUser: '',
                templateName: '',
                deleted: '',
                passed: '',
                edited: '',
                completed: ''
            },
            pageParams: {
                currentPage: 1,
                pageSize: 10,
                totalElements: 20,
                totalPages: 1
            },
            loginUser: {
                userId: '',
                username: '',
                usertype: 0
            },
            advancedSearch: false,
            contractTypes: [],
            contractTemplates: [],
            departs: [],
            users: [],
            companies: [],
            companiesA: [],
            companiesB: [],
            contractData: [],
            rules: {
                contractName: [{ required: true, message: '请输入合同名', trigger: 'blur' }],
                contractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
                companiesA: [{ required: true, message: '请选择甲方公司', trigger: 'change' }],
                companiesB: [{ required: true, message: '请选择乙方公司', trigger: 'change' }],
                contactPerson: [{ required: true, message: '请选择负责人', trigger: 'change' }],
                depart: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
                signedDate: [{ required: true, validator: checkSignedDate, trigger: ['blur', 'change'] }],
                deadline: [{ required: true, validator: checkDeadline, trigger: ['blur', 'change'] }],
                passed: [{ required: true, message: '请选择审批类型', trigger: 'blur' }],
                completed: [{ required: true, message: '是否完成', trigger: 'blur' }],
                phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
                externString: [{ validator: checkExtern, trigger: ['blur', 'change'] }],
                name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
            },
            formData: {
                contractId: '',
                contractName: '',
                contractType: '',
                depart: '',
                companiesA: [],
                companiesB: [],
                startTime: '',
                endTime: '',
                currentAmount: '',
                contractAmount: '',
                contactPerson: '',
                contactPhone: '',
                createUser: '',
                startTime1: '',
                startTime2: '',
                endTime1: '',
                endTime2: '',
                externList: [
                    {
                        name: '',
                        value: ''
                    }
                ],
                lastEditedUser: '',
                editedTime: '',
                approvalPerson: '',
                approvalContent: '',
                deleted: 0
            },
            customColors: [
                { color: '#f56c6c', percentage: 20 },
                { color: '#e6a23c', percentage: 40 },
                { color: '#5cb87a', percentage: 60 },
                { color: '#1989fa', percentage: 80 },
                { color: '#6f7ad3', percentage: 100 }
            ]
        };
    },
    created() {
        this.initData();
        // console.log(this.loginUser);
        // console.log(typeof(this.loginUser.usertype))
        // console.log(this.loginUser.usertype !== 0);
    },
    methods: {
        test() {},
        handleCancel() {
            this.editVisible = false;
        },
        handleManageAttachment(index, row) {
            let contractId = row.contractId;
            this.$router.push({
                path: `/contract/${contractId}/attachment`
            });
        },
        handleManageStatus(index, row) {
            let contractId = row.contractId;
            this.$router.push({
                path: '/contract/' + contractId + '/status'
            });
        },
        convertFormToEditParams() {
            let companiesA = [];
            this.formData.companiesA.forEach((item) => {
                companiesA.push({
                    companyId: item
                });
            });
            let companiesB = [];
            this.formData.companiesB.forEach((item) => {
                companiesB.push({
                    companyId: item
                });
            });
            let date1 = getFromDateAndTime(this.formData.startTime1, this.formData.startTime2);
            let date2 = getFromDateAndTime(this.formData.endTime1, this.formData.endTime2);

            let contract = new Object();
            contract.contractId = this.formData.contractId;
            contract.contractName = this.formData.contractName;
            contract.contractType = {
                typeId: this.formData.contractType
            };
            contract.depart = {
                departId: this.formData.depart
            };
            contract.contactPerson = this.formData.contactPerson;
            contract.contactPhone = this.formData.contactPhone;
            contract.companiesA = companiesA;
            contract.companiesB = companiesB;
            contract.startTime = dateToString(date1);
            contract.endTime = dateToString(date2);
            contract.edited = 1;
            contract.lastEditedUser = this.loginUser.username;
            contract.editedTime = dateToString(new Date());
            contract.completed = this.formData.completed;
            contract.contractAmount = this.formData.contractAmount;
            contract.externList = this.formData.externList;
            // console.log(this.formData.passed)
            if (this.loginUser.usertype === 0) {
                if (this.formData.passed === 1) {
                    contract.passedTime = dateToString(new Date());
                }
                contract.passed = this.formData.passed;
                contract.approvalPerson = this.loginUser.username;
                contract.approvalContent = this.formData.approvalContent;
            }
            return contract;
        },
        getFormDataFromRow(index, row) {
            let companiesA = [];
            this.companies.forEach((item) => {
                if (row.companiesA.split(',').some((e) => e == item.companyName)) {
                    companiesA.push(item.companyId);
                }
            });
            let companiesB = [];
            this.companies.forEach((item) => {
                if (row.companiesB.split(',').some((e) => e == item.companyName)) {
                    companiesB.push(item.companyId);
                }
            });
            let depart = '';
            for (var i in this.departs) {
                let item = this.departs[i];
                if (item.departName === row.depart) {
                    depart = item.departId;
                    break;
                }
            }
            let contractType = '';
            for (var i in this.contractTypes) {
                let item = this.contractTypes[i];
                if (item.typeName === row.contractType) {
                    contractType = item.typeId;
                    break;
                }
            }
            let createUserId = '';
            for (var i in this.users) {
                let item = this.users[i];
                if (item.username === row.createUser) {
                    createUserId = item.userId;
                    break;
                }
            }
            this.formData = row;
            this.formData.contactPerson = row.contactInfo.split('/')[0];
            this.formData.contactPhone = row.contactInfo.split('/')[1];
            this.formData.contractType = contractType;
            this.formData.depart = depart;
            this.formData.createUser = row.createUser;
            this.formData.creaetUserId = createUserId;
            this.formData.companiesA = companiesA;
            this.formData.companiesB = companiesB;
            this.formData.startTime1 = new Date(String(row.startTime));
            this.formData.startTime2 = new Date(String(row.startTime));
            this.formData.endTime1 = new Date(String(row.endTime));
            this.formData.endTime2 = new Date(String(row.endTime));
            this.formData.passedTime = new Date(String(row.passedTime));
            this.getExternString();
        },
        handleEditContract(index, row) {
            this.editVisible = true;
            let i = index;
            let r = row;
            this.getFormDataFromRow(i, row);
            //this.formData = row
        },
        handleSaveEdit() {
            let contract = this.convertFormToEditParams();
            let params = new FormData();
            params.append('contract', new Blob([JSON.stringify(contract)], { type: 'application/json' }));
            // console.log(this.formData);
            // console.log(contract);
            this.$refs.formData.validate((valid) => {
                let headers = {
                    'Content-Type': 'multipart/form-data'
                };
                if (valid) {
                    api.saveContract(params, headers)
                        .then((res) => {
                            console.log(res);
                            if (res.code === 200) {
                                this.$message.success('修改成功');
                                this.editVisible = false;
                                this.getContractData();
                            } else {
                                this.$message.error(res.msg);
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                }
            });
        },
        clearAdvancedSearch() {
            this.query = this.$options.data().query;
            this.getContractData();
        },
        handleAdvancedSearch() {
            if (this.advancedSearch == false) {
                this.advancedSearch = true;
            } else {
                this.clearAdvancedSearch();
                this.advancedSearch = false;
            }
        },
        customColorMethod(percentage) {
            if (percentage < 25) {
                return '#F56C6C';
            } else if (percentage < 50) {
                return '#E6A23C';
            } else if (percentage < 75) {
                return '#409EFF';
            } else {
                return '#67c23a';
            }
        },
        getPercentage(index, row) {
            let amount = 100;
            if (row.currentAmount === row.contractAmount) {
                return amount;
            } else {
                let amount = parseInt((row.currentAmount / row.contractAmount) * 100);
                return amount;
            }
        },
        statusFormat(percentage) {
            // console.log(percentage);
            return percentage === 0 ? 'exception' : percentage === 100 ? 'success' : '';
        },
        statusTag(index, row) {
            // console.log(row.endTime);
            let endTime = new Date(row.endTime).getTime();
            let currentTime = new Date().getTime();
            if (endTime < currentTime) {
                return true;
            } else {
                return false;
            }
        },
        resetExtern() {
            this.formData.externList = [
                {
                    name: '',
                    value: ''
                }
            ];
            this.getExternString();
        },
        closeExtern() {
            this.externVisible = false;
            this.getExternString();
        },
        handleEditExtern() {
            this.externVisible = true;
        },
        removeExtern(item) {
            var index = this.formData.externList.indexOf(item);
            if (index !== -1) {
                this.formData.externList.splice(index, 1);
            }
            this.getExternString();
        },
        addExtern() {
            this.formData.externList.push({
                name: '',
                value: '',
                key: Date.now()
            });
        },
        getExternString() {
            let list = this.formData.externList;
            let string = '';
            if (list.length > 1) {
                for (let i = 0; i < list.length - 1; i++) {
                    //console.log(list[i].value);
                    string += list[i].name + ':' + list[i].value + ',';
                }

                string += list[list.length - 1].name + ':' + list[list.length - 1].value;
            }
            if (list.length === 1) {
                string += list[list.length - 1].name + ':' + list[list.length - 1].value;
            }
            this.$set(this.formData, 'externString', string);
            // console.log(string);
            // console.log(1);
            // console.log(this.formData.externString);
        },
        initData() {
            this.getContractData();
            this.getContractTypeData();
            this.getContractTemplateData();
            this.getUserData();
            this.getDepartData();
            this.getCompanyData();
            this.loginUser.userId = localStorage.getItem('userId');
            this.loginUser.username = localStorage.getItem('username');
            this.loginUser.usertype = parseInt(localStorage.getItem('usertype'));
        },
        getContractData() {
            let currentPage = this.pageParams.currentPage;
            let pageSize = this.pageParams.pageSize;
            api.searchContract(currentPage, pageSize, this.query)
                .then((res) => {
                    if (res.code === 200) {
                        this.contractData = res.data.content;
                        this.pageParams.currentPage = res.data.currentPage;
                        this.pageParams.pageSize = res.data.pageSize;
                        this.pageParams.totalElements = res.data.totalElements;
                        this.pageParams.totalPages = res.data.totalPages;
                    }
                })
                .catch((err) => {
                    console.log('getContractData');
                    console.log(err);
                });
        },
        getCompanyData() {
            api.getAllCompanyList()
                .then((res) => {
                    if (res.code === 200) {
                        this.companiesA = res.data;
                        this.companiesB = res.data;
                        this.companies = res.data;
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        getContractTemplateData() {
            api.getAllContractTemplateList()
                .then((res) => {
                    if (res.code === 200) {
                        this.contractTemplates = res.data;
                    }
                })
                .catch((err) => {
                    console.log('getContractTemplat');
                    console.log(err);
                });
        },
        getContractTypeData() {
            api.getAllContractTypeList()
                .then((res) => {
                    if (res.code === 200) {
                        this.contractTypes = res.data;
                    }
                })
                .catch((err) => {
                    console.log('getContractTypeData');
                    console.log(err);
                });
        },
        getDepartData() {
            api.getAllDepartList()
                .then((res) => {
                    if (res.code === 200) {
                        this.departs = res.data;
                    }
                })
                .catch((err) => {
                    console.log('getDepartData');
                    console.log(err);
                });
        },
        getUserData() {
            api.getAllUserList()
                .then((res) => {
                    if (res.code === 200) {
                        this.users = res.data;
                    }
                })
                .catch((err) => {
                    console.log('getUserData');
                    console.log(err);
                });
        },
        // 触发搜索按钮
        handleSearch() {
            this.getContractData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    if (this.loginUser.usertype !== 0) {
                        this.$message.error('您不是管理员，没有权限操作');
                        return;
                    }
                    api.deleteContractById(row.contractId).then((res) => {
                        console.log(res);
                        if (res.code === 200) {
                            this.$message.success('删除成功');
                            this.initData();
                        } else {
                            this.$message.error('删除失败');
                        }
                    });
                })
                .catch(() => {});
        }
    }
};
</script>

<style>
.demo-table-expand {
    font-size: 0;
}
.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}
.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}
.el-table .cell {
    white-space: pre-line;
}
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.el-dropdown-link {
    cursor: pointer;
    color: #409eff;
}
.el-icon-arrow-down {
    font-size: 12px;
}
.demonstration {
    display: block;
    color: #8492a6;
    font-size: 14px;
    margin-bottom: 20px;
}
.form-box {
    display: inline-block;
    margin: 10px 30px;
    width: 45%;
}
</style>
